/**
 *   AVPlayerItemStatusUnknown,播放源未知
 *   AVPlayerItemStatusReadyToPlay,播放源准备好
 *   AVPlayerItemStatusFailed播放源失败
 */

#import "DNPalyerView.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "Masonry.h"

//播放器的几种状态
typedef NS_ENUM(NSInteger, DNlayerState) {
    DNPlayerStateBufferEmpty,//缓冲中
    DNPlaybackLikelyToKeepUp,    //播放中
    DNPlayerStateStopped,    //停止播放
    DNPlayerStatePause       //暂停播放
};


@interface DNPalyerView () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) AVPlayer       *player;//播放器对象
@property (nonatomic, strong) AVPlayerItem   *playerItem;//item
@property (nonatomic, strong) id             playbackTimeObserver;//监听返回值
/** 播发器的几种状态 */
@property (nonatomic, assign) DNlayerState       state;




// 播放按钮
@property (nonatomic, weak) IBOutlet UIButton *playerBtn;//播放按钮
@property (nonatomic, weak) IBOutlet UILabel  *currentTime;//当前播放的时间
@property (nonatomic, weak) IBOutlet UILabel  *totalMovieDuration;//总时间
@property (nonatomic, weak) IBOutlet UISlider *slider; //播放进度
@property (nonatomic, weak) IBOutlet UIProgressView *progressView;//缓存进度
@property (nonatomic, weak) IBOutlet UIView       *viewPlay;//播放视图
@property (nonatomic, weak) IBOutlet UIView       *viewBack;//返回视图

@property (nonatomic, weak) AVPlayerLayer *playerLayer;

@end


@implementation DNPalyerView
#pragma mark  交互
//拖动
- (void)panGesture:(UIPanGestureRecognizer *)panGR {
    
    if(panGR.numberOfTouches > 1) {
        return;
    }
    CGPoint translationPoint=[panGR translationInView:self];
    [panGR setTranslation:CGPointZero inView:self];
    
    CGFloat x = translationPoint.x;
    CGFloat y = translationPoint.y;
    //上下调节音量
    //     (x==0 && fabs(y)>=5)|| fabs(y)/ fabs(x) > = 3
    
    CGFloat ratio = ([[UIDevice currentDevice].model rangeOfString:@"iPad"].location != NSNotFound)?20000.0f:13000.0f;
    CGPoint velocity = [panGR velocityInView:self];
    
    
    //默认UI左右拖动调节进度
    //    (y==0&&fabs(x)>=5)||fabs(x)/fabs(y)>=3)
    
    [_player pause];
    
    
    
    if (panGR.state==UIGestureRecognizerStateEnded)
        //拖动手势结束
        
        
        [_player play];
    
    
    
}

/// pan手势事件
///
/// @param gesture UIPanGestureRecognizer
- (void)panDirection:(UIPanGestureRecognizer *)panGesture {

    
}


//播放完成
- (void)playbackFinished:(NSNotification *)notification {
    
    NSLog(@"播放完成");
    
}

/// 播放按钮
- (void)playerBtnClick:(UIButton *)sender {
    
    sender.selected = !sender.isSelected;
    if (sender.selected) {
        
       [_player play];
    } else {
        
         [_player pause];
    }
    
    
    
}

///点击全屏UIButton *)sender
- (IBAction)fullscreen {
    UIDeviceOrientation orientation             = [UIDevice currentDevice].orientation;
    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)orientation;
    
    [self interfaceOrientation:interfaceOrientation];
    
    
//    CGRect  frame = CGRectMake(-150, 150, [UIScreen mainScreen].bounds.size.height , self.bounds.size.width);
//    CGAffineTransform rotation = CGAffineTransformMakeRotation(M_PI_2);
//    self.frame = frame;
//    self.playerLayer.frame = self.bounds;
//    self.viewPlay.frame = self.bounds;
//    self.transform = rotation;
    //    self.viewPlay.transform = rotation;
    
}


- (void)setVideoUrlStr:(NSString *)videoUrlStr {
    _videoUrlStr = videoUrlStr;
    
    
    _playerItem = [self getPlayItemWithURLString:videoUrlStr];
    
    [self addObservers];
    
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame = self.bounds;
    playerLayer.videoGravity = AVLayerVideoGravityResize;
    
    
    [self.viewPlay.layer addSublayer:playerLayer];
    
    //    [self.layer addSublayer:playerLayer];
    
    // 如果想要自定义播放器的大小,应该自定义 --> 设置frame / 添加到视图中
    //   self.frame = CGRectMake(-150, 150, self.bounds.size.height, self.bounds.size.width);
    //   CGAffineTransform rotation = CGAffineTransformMakeRotation(M_PI_2);
    
    //    self.transform = rotation;
    
    
    
    [self.slider addTarget:self action:@selector(handleSlider:)forControlEvents:UIControlEventValueChanged];
    
    
    
    
}









#pragma mark KVO
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {
    
   
//    if (object == self.playerItem) {
    
      if([keyPath isEqualToString:@"status"]) {
        
       if (self.player.status == AVPlayerStatusReadyToPlay) {
            
            self.state = AVPlayerStatusReadyToPlay;
           // 加载完成后，再添加手势
           [self addGesture];
           
            // 获取视频总长度
            CGFloat videoDurationSeconds = CMTimeGetSeconds(self.playerItem.duration);
            
            self.totalMovieDuration.text = [self convertTime:videoDurationSeconds];
            //给slider赋值
            self.slider.maximumValue = videoDurationSeconds + 1;
            
            //设置播放按钮状态为播放
            self.playerBtn.selected = YES;
            
            [self.player play];
            //监听播放
            [self monitoringPlayback:self.playerItem];
            
            //播放源未知
        }  else if (self.player.status == AVPlayerStatusFailed) {
                    //菊花播放失败
      
        }
          
          
      } else if([keyPath isEqualToString:@"loadedTimeRanges"]){
          
          //当前缓存
          [self upDateTheNewCache];
          
      } else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) {
        
          //网络比较差 没缓存好 当缓冲是空的时候 转菊花
          if (self.playerItem.playbackBufferEmpty) {
              self.state = DNPlayerStateBufferEmpty;
          }
          
          
      } else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
          // 当缓冲好的时候
          if (self.playerItem.playbackLikelyToKeepUp){
              self.state = DNPlaybackLikelyToKeepUp;
          }
          
      }
        
        
        
        
//    }
    
   
    
    
}

///  监听播放状态
- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    
    typeof(self) waekSelf = self;
    self.playbackTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        // 计算当前在第几秒   //当前时间
        CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;
        //        waekSelf.slider.minimumValue = currentSecond;
        waekSelf.slider.value = currentSecond;
        waekSelf.currentTime.text = [waekSelf convertTime:currentSecond];
        
    }];
    
}



#pragma mark upUI



/// 强制屏幕转屏
///
/// @param orientation 屏幕方向
- (void)interfaceOrientation:(UIInterfaceOrientation)orientation {

    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector  = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = orientation;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
       
    }
    if (orientation == UIInterfaceOrientationLandscapeRight || orientation == UIInterfaceOrientationLandscapeLeft ) {
        //横屏
//        self setOrientationLandscape
    } else if (orientation == UIInterfaceOrientationPortrait) {
      //竖屏
    }
    
}

/// 横屏
- (void)setOrientationLandscape {

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    
}



///更新进度条
- (void)upDateTheNewCache {
    
    //现有缓冲总长度
    NSTimeInterval totalBuffer = [self availableDurationTimeRanges:_player.currentItem.loadedTimeRanges]/ CMTimeGetSeconds(self.playerItem.duration);
    [self.progressView   setProgress:totalBuffer animated:NO];
}



///进度条
- (void)handleSlider:(UISlider *)slider {
    
    //拖动改变视频播放进度
    if (_player.status == AVPlayerStatusReadyToPlay) {
        
        //    //计算出拖动的当前秒数
        CGFloat total = (CGFloat)_playerItem.duration.value / _playerItem.duration.timescale;
        
        //    NSLog(@"%f", total);
        
        NSInteger dragedSeconds = floorf(total * slider.value);
        
        //    NSLog(@"dragedSeconds:%ld",dragedSeconds);
        
        //转换成CMTime才能给player来控制播放进度
        
        CMTime dragedCMTime = CMTimeMake(dragedSeconds, 1);
        
        [_player pause];
        
        [_player seekToTime:dragedCMTime completionHandler:^(BOOL finish){
            
            [_player play];
            
        }];
        
    }
    
    
}

///app退到后台
- (void)applicationWillResignActiveNotification:(NSNotification *)notifcation {

}
///进入前台
- (void)applicationDidBecomeActiveNotification:(NSNotification *)notifcation {

}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

//    CGPoint point = [touch locationInView:self.controlView];//菜单View
//    // （屏幕下方slider区域） || （在cell上播放视频 && 不是全屏状态） || (播放完了) =====>  不响应pan手势
//    if ((point.y > self.bounds.size.height-40) || (self.isCellVideo && !self.isFullScreen) || self.playDidEnd) {
//        return NO;
//    }
    
    return YES;
}


/// 获取资源管理
- (AVPlayerItem *)getPlayItemWithURLString:(NSString *)urlString {
    
    if ([urlString rangeOfString:@"http"].location != NSNotFound) {
        
        AVPlayerItem *playerItem =[AVPlayerItem playerItemWithURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
        return playerItem;
    } else {
        
        AVAsset *movieAsset  = [[AVURLAsset alloc]initWithURL:[NSURL fileURLWithPath:urlString] options:nil];
        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
        return playerItem;
    }
    
}


//转换视频时间
- (NSString *)convertTime:(CGFloat)second {
    
    NSDate *data = [NSDate dateWithTimeIntervalSince1970:second];
    NSDateFormatter *formatter = [NSDateFormatter new];
    
    if (second/3600 >= 1) {
        
        [formatter setDateFormat:@"HH:mm:ss"];
    } else {
        
        [formatter setDateFormat:@"mm:ss"];
    }
    return [formatter stringFromDate:data];
}

///计算缓存进度
- (NSTimeInterval)availableDurationTimeRanges:(NSArray *)timeRanges {
    
    CMTimeRange timeRange = [timeRanges.firstObject CMTimeRangeValue];
    CGFloat startSeconds = CMTimeGetSeconds(timeRange.start);
    CGFloat durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval totalBuffer = startSeconds + durationSeconds;
    return totalBuffer;
}


+ (instancetype)playerTool {
    return  [[[NSBundle mainBundle] loadNibNamed:@"playerTool" owner:self options:nil] lastObject];
}






- (void)dealloc {
    
    [self.player removeTimeObserver:self.playbackTimeObserver];
    [self.playerItem removeObserver:self forKeyPath:@"status"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    self.playbackTimeObserver = nil;
    [self.player pause];
    self.player = nil;
    
}

#pragma mark add


- (void)addObservers {
    
    //观察playerItem的状态变化
    [self.playerItem addObserver:self forKeyPath:@"status"options:NSKeyValueObservingOptionNew context:nil];
    
    //加载缓存
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges"options:NSKeyValueObservingOptionNew context:nil];
    
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:)name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

/// 添加观察者、通知
- (void)addAddObserverAndNotification {
    
    //app进入后台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActiveNotification:) name:UIApplicationWillResignActiveNotification object:nil];
    //前台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActiveNotification:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

///添加盘手势
- (void)addGesture {
    
    // 添加平移手势，用来控制音量、亮度、快进快退
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panDirection:)];
    pan.delegate = self;
    [self addGestureRecognizer:pan];
    
}

///播放器对象
- (AVPlayer *)player {
    
    if(_player == nil) {
        
        _player = [AVPlayer playerWithPlayerItem:self.playerItem];
    }
    return _player;
}

@end
